<!--upload video for jobGroup-->
<template>
    <el-card shadow="hover">
        <div class="custom-table-header">
            <span class="custom-table-header-cell">当前选定的工作组序号为: {{ currentJobGroupId || 'null' }}</span>
        </div>
    </el-card>
    <el-card shadow="hover">
        <div class="upload-container">
            <div class="upload-item">
                <video controls style="max-width: 100%; height: auto;" ref="sourcePreview"></video>
                <el-upload limit="1" @change="changeSourceFile" :auto-upload="false" :data="uploadForm.data"
                    ref="uploadSource">
                    <el-button class="upload-button" size="medium" type="primary">选取原视频</el-button>

                </el-upload>
                <el-button class="upload-button" size="medium" type="success"
                        @click="submitUpload(0)">上传原视频到服务器</el-button>

            </div>
        </div>
    </el-card>
    <el-card shadow="hover">
        <div class="upload-container">
            <div class="upload-item">
                <video controls style="max-width: 100%; height: auto;" ref="targetPreview"></video>
                <el-upload limit="1" @change="changeTargetFile" :auto-upload="false" :data="uploadForm.data"
                    ref="uploadTarget">
                    <el-button class="upload-button" size="medium" type="primary">选取目标视频</el-button>

                </el-upload>
                <el-button class="upload-button" size="medium" type="success"
                        @click="submitUpload(1)">上传目标视频到服务器</el-button>

            </div>
        </div>
    </el-card>
</template>

<script setup>
import { reactive, ref, toRefs, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiUploadFile, saveFaceJob, updateFaceJob, FaceJobPage, delFaceJob, startJob } from '../../api/systemApi.js';
import { useJobGroupStore, useJobStore } from '../../store/settings';
import { now } from '@vueuse/shared';

const jobGroupStore = useJobGroupStore();
const jobStore = useJobStore();

const currentJobGroupId = jobGroupStore.getJobGroupId
const fpsOptions = [24, 30, 60];

const file = ref(null);
const sourcePreview = ref(null);
const targetPreview = ref(null);


const state = reactive({
    jobForm: {
        jobName: '',
        jobGroupId: currentJobGroupId,
        outputExt: '',
        fps: '',
        jobSort: 1,
        command: "step1_extract_images_from_video_data_src.bat"
    },
    operate: 0,
    sourceFile: null,
    targetFile: null
})

const { jobForm, operate, sourceFile, targetFile } = toRefs(state);

// 表单验证规则
const rules = {
    jobName: [
        { required: true, message: '请输入名称', trigger: 'blur' },
        // 可添加其他验证规则
    ],
    fps: [
        { required: true, message: '请选择FPS', trigger: 'change' },
    ],
    outputExt: [
        { required: true, message: '请选择输出格式', trigger: 'change' },
    ],
};

const uploadForm = reactive({
    data: {
        file: '',
        jobGroupId: '',
        fileNowName: ''
    }
})

function changeSourceFile(file) {
    previewVideo(file, sourcePreview.value);
    state.sourceFile = file.raw;
}

function changeTargetFile(file) {
    previewVideo(file, targetPreview.value);
    state.targetFile = file.raw;
}

function previewVideo(file, videoElement) {
    if (!file.raw) return;
    const videoURL = URL.createObjectURL(file.raw);
    videoElement.src = videoURL;
    videoElement.play().catch(error => console.error("Error trying to play video:", error));
}

const createFileChunks = (file, chunkSize = 2 * 1024 * 1024) => {  // 默认分片大小为MB
    const chunks = [];
    let currentPosition = 0;

    while (currentPosition < file.size) {
        const chunk = file.slice(currentPosition, currentPosition + chunkSize);
        chunks.push(chunk);
        currentPosition += chunkSize;
    }
    return chunks;
};

const submitUpload = (type) => {
    const nowfile = type === 0 ? state.sourceFile : state.targetFile;
    if (!nowfile) {
        ElMessage.error({
            message: "请选择要上传的文件",
            type: 'error'
        });
        return;
    }

    const chunks = createFileChunks(nowfile);
    const totalChunks = chunks.length;
    console.log("rotal",totalChunks)
    let chunkNumber = 0;

    //chunks.forEach(chunk => {
        const formData = new FormData();
        formData.append('jobGroupId', currentJobGroupId);
        //formData.append('file', chunk);
        formData.append('file', nowfile);
        formData.append('fileNowName', type === 0 ? 'data_src' : 'data_dst');
        //formData.append('chunkNumber', ++chunkNumber);
        formData.append('totalChunks', totalChunks);

        apiUploadFile(formData)
            .then(response => {
                if (response.code == 200) {
                    console.log("!!!")
                    ElMessage.success({
                        message: '文件分片上传完成',
                        type: 'success'
                    });

                } else {
                    ElMessage.warn({
                        message: `分片 上传失败`,
                        type: 'warning'
                    });
                }
            })
            .catch(error => {
                console.error(`分片上传失败`, error);
                // 这里可以根据错误情况进行处理
            });
    //});
};



const submitUpload_withoutchunk = (type) => {
    let nowfile = type === 0 ? state.sourceFile : state.targetFile;
    if (!nowfile) {
        ElMessage.error({
            message: "请选择要上传的文件",
            type: 'error'
        });
        return;
    }
    const formData = new FormData();
    formData.append('jobGroupId', currentJobGroupId);
    formData.append('file', nowfile);
    formData.append('fileNowName', type === 0 ? 'data_src' : 'data_dst')

    apiUploadFile(formData).then(response => {
        if (response.code == 200) {
            ElMessage.success({
                message: '上传成功',
                type: 'success'
            });
        } else {
            ElMessage.warn({
                message: '上传失败',
                type: 'success'
            });
        }
    }).catch(error => {
        console.error('文件上传失败', error);
        // 这里可以根据错误情况进行处理
    });
};


</script>

<style scoped>
.custom-table-header {
    display: flex;
    justify-content: center;

    /* 如果你想要文字居中 */
    background-color: #eff4f9;
    /* 表头背景色 */
    color: #606266;
    /* 表头文字颜色 */
    font-weight: bold;
    /* 表头文字加粗 */
    padding: 10px 0;
    /* 表头内部上下填充 */
    border-bottom: 1px solid #ebeef5;
    /* 表头下边框 */
    font-size: 17px;
    /* 增大字体大小 */
    letter-spacing: 2px;
    /* 增大字间距 */
}

.custom-table-header-cell {
    text-align: center;
    width: 100%;
    /* 单元格宽度为100%，这样文字就会填满整个表头 */
}

.upload-container {
    display: flex;
    width: 75%;
    /* justify-content: center; */
    transform: translateX(25%);
    align-items: center;
    /* 垂直居中 */
    background-color: #e5f6f18b;
    overflow-x: auto;
}

.buttons-column {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    /* 按钮顶部对齐 */
    gap: 20px;
    /* 按钮之间的间隔 */
    padding-right: 20px;
    /* 与视频预览之间的间距 */
}

.preview-column {
    display: flex;
    flex-direction: column;
    justify-content: center;
    /* 视频预览垂直居中 */
}

.upload-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    background-color: #e5f6f18b;
    width: 100%;
    /* 默认宽度为100%，但会因flex布局自适应 */
    max-width: 300px;
    /* 最大宽度，根据实际情况调整 */
    /* 增加间距 */
}

.upload-button {
    margin-top: 20px;
    /* 增加按钮之间的间距 */
    margin-left: 20px;
    width: auto;
    justify-content: space-evenly
}

.upload-column {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 33.33%;
    /* 三列布局，每列占据1/3宽度 */
}

video {
    max-width: 100%;
    /* 视频最大宽度为100%，保证不超出容器 */
    height: auto;
    /* 高度自动 */
}
</style>
